﻿using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inaction.UI.Extensions.ControlExtensions.Grid
{
    class GridExportHelper
    {
        public GridExportHelper(GridView view)
        {
            if (BarManager.GetBarManager(view.GridControl.FindForm()) == null) return;
            view.PopupMenuShowing += tree_PopupMenuShowing;
        }

        void tree_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            if (e.Menu == null) return;
            var view = sender as GridView;
            if (view == null) return;
            var itemExport = e.Menu.Items.Cast<DevExpress.Utils.Menu.DXMenuItem>().FirstOrDefault(p => p.Caption == "导出");
            if (itemExport == null)
            {
                itemExport = new DevExpress.Utils.Menu.DXMenuItem("导出");
                itemExport.Image = Properties.Resources.Export;
                e.Menu.Items.Insert(0, itemExport);
                itemExport.Tag = view;
                itemExport.Click += new EventHandler(Export_Click);
            }
            itemExport.Visible = view.GridControl.DataSource != null;
        }

        static void Export_Click(object sender, EventArgs e)
        {
            var item = sender as DevExpress.Utils.Menu.DXMenuItem;
            var view = item.Tag as GridView;
            Inaction.UI.Common.ControlHelper.ExportToExcelFile(view.GridControl);
        }
    }
}
